package com.lagou.rpc.provider;

import com.lagou.rpc.provider.handler.RpcServerHandler;
import com.lagou.rpc.provider.server.RpcServer;
import com.lagou.rpc.provider.server.config.ServerConfig;
import com.lagou.rpc.zookeeper.ZookeeperClient;
import com.lagou.rpc.zookeeper.config.ZookeeperConfig;

import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.Map;

@SpringBootApplication
public class ServerBootStrapApplication implements CommandLineRunner {
    //服务端默认端口号
    private static int port = 8991;
    private static final String IP = "127.0.0.1";
    //zookeeper连接地址
    private static final String ZOOKEEPER_ADDRESS = "106.75.185.109:2181";
    @Autowired
    RpcServer rpcServer;

    public static void main(String[] args) {

        if (args.length > 0 && NumberUtils.isDigits(args[0])) {
            port = Integer.parseInt(args[0]);
        }

        //封装服务端zookeeper配置信息
        ZookeeperConfig zookeeperConfig = ZookeeperConfig.getInstance();
        zookeeperConfig.setZookeeperAddress(ZOOKEEPER_ADDRESS);
        zookeeperConfig.setProviderSide(true);
        //启动springboot服务
        SpringApplication.run(ServerBootStrapApplication.class, args);
    }

    /**
     * springboot启动时初始化
     * @param args
     * @throws Exception
     */
    @Override
    public void run(String... args) throws Exception {
        //获取到启动时得到的服务列表
        Map serviceInstanceMap = RpcServerHandler.SERVICE_INSTANCE_MAP;

        ServerConfig serverConfig = new ServerConfig();
        serverConfig.setApplicationName("lg-provider");
        serverConfig.setIp(IP);
        serverConfig.setPort(port);
        serverConfig.setServiceMap(serviceInstanceMap);
        ZookeeperClient zookeeperClient = new ZookeeperClient(ZookeeperConfig.getInstance());
        new Thread(new Runnable() {
            @Override
            public void run() {
                rpcServer.startServer(serverConfig ,zookeeperClient);
            }
        }).start();
    }
}
